Skip to content

feat: support web search for zhipu via web_search_options#4516

Open
feitianbubu wants to merge 1 commit intoQuantumNous:mainfrom
feitianbubu:pr/4bd6a62c61bd74aad2d486367086379a3698967d
Open

feat: support web search for zhipu via web_search_options#4516
feitianbubu wants to merge 1 commit intoQuantumNous:mainfrom
feitianbubu:pr/4bd6a62c61bd74aad2d486367086379a3698967d

Conversation

@feitianbubu
Copy link
Copy Markdown
Contributor

@feitianbubu feitianbubu commented Apr 28, 2026

⚠️ 提交说明 / PR Notice

增加智谱官方支持的web search功能

📝 变更描述 / Description

智谱的web search 与 OpenAI的格式不兼容
https://docs.z.ai/api-reference/llm/chat-completion
因此要进行转换

🚀 变更类型 / Type of change

将OpenAI标准的web search格式
转换为智谱的格式

📸 运行证明 / Proof of Work

请求:

curl http://localhost:3000/v1/chat/completions \
  --request POST \
  --header 'Authorization: ' \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "glm-5.1",
  "messages": [
    {
      "role": "user",
      "content": "今天福州天气?"
    }
  ],
  "web_search_options": {
    "search_context_size": "low"
  }
}'

返回:
image

Summary by CodeRabbit

  • New Features
    • Integrated web search functionality into the Zhipu channel. Users can now enable web search with configurable parameters including search type selection, result count, and optional content size settings.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 28, 2026

Walkthrough

The changes add web search capability to the Zhipu API adapter by introducing a post-processing step in the OpenAI request conversion. A new helper function injects web search parameters into the Zhipu request payload when web search options are provided.

Changes

Cohort / File(s) Summary
Web Search Injection
relay/channel/zhipu_4v/adaptor.go, relay/channel/zhipu_4v/relay-zhipu_v4.go
Modified ConvertOpenAIRequest to invoke new injectZhipuWebSearch helper for post-processing. Added helper function that conditionally injects a web_search tool into the Zhipu request payload with configurable search parameters (search_pro_jina, count, content_size) when web search options are present.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 Whiskers twitching with glee,
A web search tool, so keen to be free,
Injected with care in the Zhipu flow,
Adapters dance and requests now glow!
Knowledge unbounded, the AI can see! 🔍✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately and concisely describes the main change: adding web search support for Zhipu via web_search_options parameter. It is specific, clear, and directly reflects the core functionality being implemented.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
relay/channel/zhipu_4v/relay-zhipu_v4.go (1)

71-76: Normalize search_context_size before switching.

Current matching is case-sensitive; "Low"/"HIGH" silently miss the intended mapping. Normalizing input makes behavior more robust without changing semantics.

Proposed refactor
-	switch opts.SearchContextSize {
+	switch strings.ToLower(strings.TrimSpace(opts.SearchContextSize)) {
 	case "low":
 		ws["count"] = 5
 	case "high":
 		ws["count"] = 15
 		ws["content_size"] = "high"
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@relay/channel/zhipu_4v/relay-zhipu_v4.go` around lines 71 - 76, Normalize
opts.SearchContextSize before the switch so casing doesn't change behavior:
convert opts.SearchContextSize to a canonical form (e.g.,
strings.ToLower/strings.ToLower(strings.TrimSpace(...))) and switch on that
normalized value in the block that sets ws["count"] and ws["content_size"]
(referencing opts.SearchContextSize, ws["count"], and ws["content_size"] to
locate the code).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@relay/channel/zhipu_4v/relay-zhipu_v4.go`:
- Around line 78-80: The current code unconditionally appends a new web_search
tool to m["tools"], causing duplicates; instead, convert m["tools"] to a []any
(as done with tools), iterate its elements (expect map[string]any or
map[any]any), and if an element's "type" == "web_search" update that element's
"web_search" field with ws and set a flag; after the loop, if no existing
web_search was found append the new
map[string]any{"type":"web_search","web_search":ws}; finally assign the modified
slice back to m["tools"] (references: req.ToMap(), m, tools, "web_search").

---

Nitpick comments:
In `@relay/channel/zhipu_4v/relay-zhipu_v4.go`:
- Around line 71-76: Normalize opts.SearchContextSize before the switch so
casing doesn't change behavior: convert opts.SearchContextSize to a canonical
form (e.g., strings.ToLower/strings.ToLower(strings.TrimSpace(...))) and switch
on that normalized value in the block that sets ws["count"] and
ws["content_size"] (referencing opts.SearchContextSize, ws["count"], and
ws["content_size"] to locate the code).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 74be54c5-92e8-4b8c-baab-ea5d5e113fec

📥 Commits

Reviewing files that changed from the base of the PR and between db48108 and 1b8f097.

📒 Files selected for processing (2)
  • relay/channel/zhipu_4v/adaptor.go
  • relay/channel/zhipu_4v/relay-zhipu_v4.go

Comment on lines +78 to +80
m := req.ToMap()
tools, _ := m["tools"].([]any)
m["tools"] = append(tools, map[string]any{"type": "web_search", "web_search": ws})
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Avoid duplicating web_search tools in payload.

If tools already contains a type: "web_search" entry, this logic appends another one instead of updating it, which can produce an invalid/ambiguous upstream request.

Proposed fix
 	m := req.ToMap()
-	tools, _ := m["tools"].([]any)
-	m["tools"] = append(tools, map[string]any{"type": "web_search", "web_search": ws})
+	tools, _ := m["tools"].([]any)
+	updated := false
+	for i, t := range tools {
+		tool, ok := t.(map[string]any)
+		if !ok {
+			continue
+		}
+		if typ, _ := tool["type"].(string); typ == "web_search" {
+			tool["web_search"] = ws
+			tools[i] = tool
+			updated = true
+			break
+		}
+	}
+	if !updated {
+		tools = append(tools, map[string]any{"type": "web_search", "web_search": ws})
+	}
+	m["tools"] = tools
 	return m
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
m := req.ToMap()
tools, _ := m["tools"].([]any)
m["tools"] = append(tools, map[string]any{"type": "web_search", "web_search": ws})
m := req.ToMap()
tools, _ := m["tools"].([]any)
updated := false
for i, t := range tools {
tool, ok := t.(map[string]any)
if !ok {
continue
}
if typ, _ := tool["type"].(string); typ == "web_search" {
tool["web_search"] = ws
tools[i] = tool
updated = true
break
}
}
if !updated {
tools = append(tools, map[string]any{"type": "web_search", "web_search": ws})
}
m["tools"] = tools
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@relay/channel/zhipu_4v/relay-zhipu_v4.go` around lines 78 - 80, The current
code unconditionally appends a new web_search tool to m["tools"], causing
duplicates; instead, convert m["tools"] to a []any (as done with tools), iterate
its elements (expect map[string]any or map[any]any), and if an element's "type"
== "web_search" update that element's "web_search" field with ws and set a flag;
after the loop, if no existing web_search was found append the new
map[string]any{"type":"web_search","web_search":ws}; finally assign the modified
slice back to m["tools"] (references: req.ToMap(), m, tools, "web_search").

@Calcium-Ion
Copy link
Copy Markdown
Member

这个适配新版的函数计费不

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants